#!/usr/bin/python
#Saves and retrieves

import gnomekeyring
import getpass

class Keyring(object):
    def __init__(self, name, server, protocol):
        self._name = name
        self._server = server
        self._protocol = protocol
        self._keyring = gnomekeyring.get_default_keyring_sync()

    def has_credentials(self):
        try:
            attrs = {"server": self._server, "protocol": self._protocol}
            items = gnomekeyring.find_items_sync(gnomekeyring.ITEM_NETWORK_PASSWORD, attrs)
            return len(items) > 0
        except gnomekeyring.DeniedError:
            return False
        except gnomekeyring.NoMatchError:
            return False

    def get_credentials(self):
        attrs = {"server": self._server, "protocol": self._protocol}
        items = gnomekeyring.find_items_sync(gnomekeyring.ITEM_NETWORK_PASSWORD, attrs)
        return (items[0].attributes["user"], items[0].secret)

    def set_credentials(self, (user, pw)):
        attrs = {
                "user": user,
                "server": self._server,
                "protocol": self._protocol,
            }
        gnomekeyring.item_create_sync(gnomekeyring.get_default_keyring_sync(),
                gnomekeyring.ITEM_NETWORK_PASSWORD, self._name, attrs, pw, True)

    def del_credentials(self):
        attrs = {"server" : self._server, "protocol" : self._protocol}
        items = gnomekeyring.find_items_sync(gnomekeyring.ITEM_NETWORK_PASSWORD, attrs)
        for item in items:
            gnomekeyring.item_delete_sync(None, item.item_id)


def GetCred(credel):
	keyring = Keyring("Gmail Auth", "gmail.com", "http")
	if(credel==1):
		keyring.del_credentials()
	else:
		pass

	if not(keyring.has_credentials()):
		print "No stored password"
		gmailusername=raw_input("""Enter you gmail username:\n""")
		gmailpassword=getpass.getpass("""Enter your gmail password (Will not be echoed.):\n""")
		keyring.set_credentials( (gmailusername ,gmailpassword) )
	else:
#		print "Password already stored, delete it from Seahorse, if you wish to change it."
		gmailusername = keyring.get_credentials()[0]
		gmailpassword = keyring.get_credentials()[1]
	return [gmailusername,gmailpassword]
